package com.ecole.mines.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;

import android.os.AsyncTask;

public class Connexion extends AsyncTask<String, Integer, Boolean> {
	private OnTaskCompleted listener;
	
	public Connexion(OnTaskCompleted listener) {
		super();
		this.listener = listener;
	}

	public boolean verif(String code) {
		try {
			String hashServeur = getHash();
			JSONObject jo = new JSONObject(hashServeur);
			System.out.println(hashServeur);
			if (jo.get("hash").equals(hash(code)))
				return true;
		} catch (Exception e) {
			// Toast.makeText(getApplication(),
			// "Le serveur d'authentification ne r�pond pas",
			// Toast.LENGTH_SHORT).show();
			e.printStackTrace();
		}
		return false;
	}

	public String hash(String password) throws NoSuchAlgorithmException {
		String prefix = "jkhg4579843kipzvjty";
		String sufix = "v57k89ui4b65hg4ijuy";
		password = prefix + password + sufix;

		MessageDigest md = MessageDigest.getInstance("SHA-256");
		md.update(password.getBytes());

		byte byteData[] = md.digest();

		// convert the byte to hex format method 1
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < byteData.length; i++) {
			sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16)
					.substring(1));
		}

		System.out.println("Hex format : " + sb.toString());
		// convert the byte to hex format method 2
		StringBuffer hexString = new StringBuffer();
		for (int i = 0; i < byteData.length; i++) {
			String hex = Integer.toHexString(0xff & byteData[i]);
			if (hex.length() == 1)
				hexString.append('0');
			hexString.append(hex);
		}
		// System.out.println("Hex format : " + hexString.toString());
		return hexString.toString();
	}

	public String getHash() throws Exception {
		// Create a new HttpClient and Post Header
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost(
				"http://loris-jacquy.ovh/tablette/login");

		try { // Add your data
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
			// nameValuePairs.add(new BasicNameValuePair("id", "12345"));
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

			// Execute HTTP Post Request
			HttpResponse response = httpclient.execute(httppost);

			InputStream ips = response.getEntity().getContent();
			BufferedReader buf = new BufferedReader(new InputStreamReader(ips,
					"UTF-8"));
			if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
				throw new Exception(response.getStatusLine().getReasonPhrase());
			}
			StringBuilder sb = new StringBuilder();
			String s;
			while (true) {
				s = buf.readLine();
				if (s == null || s.length() == 0)
					break;

				sb.append(s);

			}
			buf.close();
			ips.close();
			return sb.toString();

		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
		}

		catch (IOException e) {
		}
		// TODO Auto-generated catch block }

		return null;
	}
	
	@Override
	protected void onPostExecute(Boolean result) 
	{
		listener.onTaskCompletedPin(result);
	}

	@Override
	protected Boolean doInBackground(String... params) {
		return verif(params[0]);
	}

}
